package dbops

import (
	_ "database/sql"
	"gitee.com/DengAnbang/Wefore/src/bean"
	"gitee.com/DengAnbang/goutils/dbutils"
	"gitee.com/DengAnbang/goutils/utils"
	"strings"
)

type PermissionBean struct {
	PermissionId       string `json:"permission_id"`
	PermissionName     string `json:"permission_name"`
	PermissionCode     string `json:"permission_code"`
	PermissionParentId string `json:"permission_parent_id"`
}

func NewPermissionBean(data map[string]string) *PermissionBean {
	return &PermissionBean{
		PermissionId:       data["permission_id"],
		PermissionCode:     data["permission_code"],
		PermissionName:     data["permission_name"],
		PermissionParentId: data["permission_parent_id"],
	}
}

type CharacterBean struct {
	CharacterId   string `json:"character_id"`
	CharacterName string `json:"character_name"`
}

func NewCharacterBean(data map[string]string) *CharacterBean {
	return &CharacterBean{
		CharacterId:   data["character_id"],
		CharacterName: data["character_name"],
	}
}
func PermissionAdd(permissionName, permissionCode, permissionParentId string) (PermissionBean, error) {
	permissionBean := PermissionBean{}
	if len(permissionName) == 0 {
		return permissionBean, bean.NewErrorMessage("权限名称不能为空")
	}
	if len(permissionCode) == 0 {
		return permissionBean, bean.NewErrorMessage("权限代号不能为空")
	}
	if len(permissionParentId) == 0 {
		permissionParentId = "0"
	}
	permissionBean, err := PermissionSelect(permissionCode)
	if err != nil {
		return permissionBean, err
	}
	if len(permissionBean.PermissionName) > 0 {
		return permissionBean, bean.NewErrorMessage("权限代号已经被使用了,使用的权限名称为:" + permissionBean.PermissionName)
	}
	uuid := utils.NewUUID()
	stmtIn, err := dbConn.Prepare("INSERT INTO table_tree_permission (permission_id,permission_name,permission_code,permission_parent_id)VALUES(?,?,?,?)")
	if err != nil {
		return permissionBean, err
	}
	_, err = stmtIn.Exec(uuid, permissionName, permissionCode, permissionParentId)
	stmtIn.Close()
	permissionBean.PermissionId = uuid
	permissionBean.PermissionCode = permissionCode
	permissionBean.PermissionName = permissionName
	permissionBean.PermissionParentId = permissionParentId
	return permissionBean, nil
}

func PermissionUpdate(permissionId, permissionName, permissionNewCode string) error {
	if len(permissionId) == 0 {
		return bean.NewErrorMessage("权限ID不能为空")
	}
	permissionBean, err := PermissionSelect(permissionNewCode)
	if err != nil {
		return err
	}
	if len(permissionBean.PermissionName) > 0 {
		return bean.NewErrorMessage("权限代号已经被使用了,使用的权限名称为:" + permissionBean.PermissionName)
	}
	stmtIn, err := dbConn.Prepare("UPDATE  table_tree_permission SET permission_name=?, permission_code=? WHERE permission_id=?")
	if err != nil {
		return err
	}
	_, err = stmtIn.Exec(permissionName, permissionNewCode, permissionId)
	defer stmtIn.Close()
	return nil
}
func PermissionDelete(permissionId string) error {
	if len(permissionId) == 0 {
		return bean.NewErrorMessage("权限id不能为空")
	}
	beans, err := PermissionTreeChildNodeSelectAll(permissionId)
	if err != nil {
		return err
	}
	for _, v := range beans {
		stmtIn, err := dbConn.Prepare("DELETE FROM table_tree_permission WHERE permission_id=?")
		if err != nil {
			return err
		}
		_, err = stmtIn.Exec(v.PermissionId)
		stmtIn.Close()
		stmtIn, err = dbConn.Prepare("DELETE FROM table_character_permission WHERE permission_id=?")
		if err != nil {
			return err
		}
		_, err = stmtIn.Exec(v.PermissionId)
		stmtIn.Close()
	}

	return nil
}

//查询所有子节点树节点的信息
func PermissionTreeChildNodeSelectAll(nodeId string) ([]PermissionBean, error) {
	//使用递归的方法
	_, err := dbConn.Exec(`DROP FUNCTION IF EXISTS get_child_list_table_tree_permission ;`)
	_, err = dbConn.Exec(`
CREATE FUNCTION  get_child_list_table_tree_permission(rootId VARCHAR(64))
  RETURNS VARCHAR(1000)
DETERMINISTIC
  BEGIN
    DECLARE sTemp VARCHAR(1000);
    DECLARE sTempChd VARCHAR(1000);
    SET sTemp = '$';
    SET sTempChd = cast(rootId AS CHAR);
    WHILE sTempChd IS NOT NULL DO
      SET sTemp = concat(sTemp, ',', sTempChd);
      SELECT group_concat(permission_id)
      INTO sTempChd
      FROM table_tree_permission
      WHERE FIND_IN_SET(permission_parent_id, sTempChd) > 0;
    END WHILE;
    RETURN sTemp;
  END`)
	var beans = make([]PermissionBean, 0)
	if err != nil {
		return beans, err
	}
	stmtOut, err := dbConn.Prepare("SELECT * FROM table_tree_permission WHERE FIND_IN_SET(permission_id, get_child_list_table_tree_structure(?))")

	if err != nil {
		return beans, err
	}
	defer stmtOut.Close()
	rows, err := stmtOut.Query(nodeId)
	if err != nil {
		return beans, err
	}
	defer rows.Close()
	for rows.Next() {
		var stringMap map[string]string
		stringMap, err = dbutils.GetRowsMap(rows)
		if err != nil {
			return beans, err
		}
		if nodeId == stringMap["node_id"] {
			continue
		}
		beans = append(beans, *NewPermissionBean(stringMap))
	}
	return beans, err
}

func PermissionSelect(permissionCode string) (PermissionBean, error) {
	var permissionBean PermissionBean
	if len(permissionCode) == 0 {
		return permissionBean, bean.NewErrorMessage("权限Code不能为空")
	}
	stmtOut, err := dbConn.Prepare("SELECT * FROM table_tree_permission WHERE permission_code = ?")
	if err != nil {
		return permissionBean, err
	}
	defer stmtOut.Close()
	rows, err := stmtOut.Query(permissionCode)
	if err != nil {
		return permissionBean, err
	}
	defer rows.Close()
	if rows.Next() {
		mapStrings, err := dbutils.GetRowsMap(rows)
		if err != nil {
			return permissionBean, err
		}
		permissionBean = *NewPermissionBean(mapStrings)
	}
	return permissionBean, nil
}
func PermissionSelectList() ([]PermissionBean, error) {
	var permissionBean = make([]PermissionBean, 0)

	stmtOut, err := dbConn.Prepare("SELECT * FROM table_tree_permission")
	if err != nil {
		return permissionBean, err
	}
	defer stmtOut.Close()
	rows, err := stmtOut.Query()
	if err != nil {
		return permissionBean, err
	}
	defer rows.Close()
	for rows.Next() {
		mapStrings, err := dbutils.GetRowsMap(rows)
		if err != nil {
			return permissionBean, err
		}
		p := *NewPermissionBean(mapStrings)
		permissionBean = append(permissionBean, p)
	}

	return permissionBean, nil
}

//todo 这里没有判断是否存在两个表,可能存在冗余数据
func PermissionToStructureTreeAdd(character_id string, permissionId string) error {
	if len(character_id) == 0 {
		return bean.NewErrorMessage("节点ID不能为空")
	}
	permissionIds := strings.Split(permissionId, ",")
	if len(permissionIds) == 0 {
		return bean.NewErrorMessage("权限ID不能为空")
	}
	stmtIn, err := dbConn.Prepare("REPLACE INTO table_character_permission (character_id,permission_id)VALUES(?,?)")
	if err != nil {
		return err
	}
	for _, v := range permissionIds {
		if len(v) != 0 {
			_, err = stmtIn.Exec(character_id, v)
		}
	}
	if err != nil {
		return err
	}
	return nil
}

//删除权限
func PermissionToStructureTreeDelete(character_id string, permissionId string) error {
	if len(character_id) == 0 {
		return bean.NewErrorMessage("角色ID不能为空")
	}
	permissionIds := strings.Split(permissionId, ",")
	if len(permissionIds) == 0 {
		return bean.NewErrorMessage("权限ID不能为空")
	}
	stmtIn, err := dbConn.Prepare("DELETE FROM table_character_permission WHERE node_id=? AND permission_id=?")
	if err != nil {
		return err
	}
	for _, v := range permissionIds {
		if len(v) != 0 {
			_, err = stmtIn.Exec(character_id, v)
		}
	}
	if err != nil {
		return err
	}
	return nil
}

//查询角色权限
func PermissionToStructureTreeSelect(character_id string) ([]PermissionBean, error) {
	beans := make([]PermissionBean, 0)
	if len(character_id) == 0 {
		return beans, bean.NewErrorMessage("节点ID不能为空")
	}
	stmtOut, err := dbConn.Prepare("SELECT * FROM table_character_permission LEFT OUTER JOIN table_tree_permission ON table_character_permission.permission_id=table_tree_permission.permission_id WHERE character_id=?")
	if err != nil {
		return beans, err
	}
	defer stmtOut.Close()
	rows, err := stmtOut.Query(character_id)
	if err != nil {
		return beans, err
	}
	defer rows.Close()
	for rows.Next() {
		mapStrings, err := dbutils.GetRowsMap(rows)
		if err != nil {
			return beans, err
		}
		permissionBean := *NewPermissionBean(mapStrings)
		if len(permissionBean.PermissionCode) != 0 {
			beans = append(beans, permissionBean)
		}
	}
	return beans, err
}

//创建角色
func CharacterAdd(name string) error {
	if len(name) == 0 {
		return bean.NewErrorMessage("角色名称不能为空")
		//return user, httpUtils.NewResultError(code.NormalErr, "账号不能为空")
	}
	characterBean, err := CharacterSelect(name)
	if err != nil {
		return err
	}
	if len(characterBean.CharacterName) > 0 {
		return bean.NewErrorMessage("角色名称已经存在了")
	}
	stmtIn, err := dbConn.Prepare("INSERT INTO table_character (name)VALUES(?)")
	if err != nil {
		return err
	}
	_, err = stmtIn.Exec(name)
	_ = stmtIn.Close()
	return nil
}

//查询角色
func CharacterSelect(name string) (CharacterBean, error) {
	var characterBean CharacterBean
	if len(name) == 0 {
		return characterBean, bean.NewErrorMessage("角色名称不能为空")
	}
	stmtOut, err := dbConn.Prepare("SELECT * FROM table_character WHERE name=?")
	defer stmtOut.Close()
	rows, err := stmtOut.Query(name)
	if err != nil {
		return characterBean, err
	}
	defer rows.Close()
	if rows.Next() {
		mapStrings, err := dbutils.GetRowsMap(rows)
		if err != nil {
			return characterBean, err
		}
		characterBean = *NewCharacterBean(mapStrings)
	}
	return characterBean, err
}

//查询所有角色
func CharacterSelectAll() ([]CharacterBean, error) {
	beans := make([]CharacterBean, 0)
	stmtOut, err := dbConn.Prepare("SELECT * FROM table_character")
	defer stmtOut.Close()
	rows, err := stmtOut.Query()
	if err != nil {
		return beans, err
	}
	defer rows.Close()
	for rows.Next() {
		mapStrings, err := dbutils.GetRowsMap(rows)
		if err != nil {
			return beans, err
		}
		character := *NewCharacterBean(mapStrings)
		if len(character.CharacterName) != 0 {
			beans = append(beans, character)
		}
	}
	return beans, err
}

//删除角色
func CharacterDelete(name string) error {
	if len(name) == 0 {
		return bean.NewErrorMessage("角色名称不能为空")
	}
	stmtIn, err := dbConn.Prepare("DELETE FROM table_character WHERE name=?")
	if err != nil {
		return err
	}
	_, err = stmtIn.Exec(name)
	_ = stmtIn.Close()
	return nil
}
